<template>
  <div class="w-full">
    <ProTable
      ref="tableRef"
      :fetchListApi="_fetchSoftwareLogCheck"
      :columns="columns"
      :hide-search="true"
      :height="500"
    >
      <template #monitorStatus="{ record }">
        <Switch
          :checked="record.monitorStatus"
          checked-value="1"
          un-checked-value="0"
          @change="(checked) => onChangeMonitorStatus(checked as string, record)"
        ></Switch>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { Modal, Switch, Tag } from 'ant-design-vue';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { listToEnum } from '@/utils/utils';
import { fetchDictsOfType } from '@/api/dict';
import { firmCancelMonitor, firmPushLogCheck } from '@/api/push';

const props = defineProps({
  update: {
    type: Object,
    default: () => ({}),
  },
  // target: {
  //   type: String,
  //   default: () => '',
  // },
});

// const switchLoad = ref(false);
// const loading = ref(true);
// const dataList = ref([]);
// const queryParams = ref({
//   pageNum: 1,
//   pageSize: 10,
// });
const sysOnlineStatusEnum = ref<Record<string, any>>({});
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '推送时间',
    dataIndex: 'upgradeTime',
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
  },
  {
    title: '设备类型',
    dataIndex: 'deviceTypeLabel',
  },
  {
    title: '设备型号',
    dataIndex: 'model',
  },
  {
    title: '所属项目',
    dataIndex: 'projectName',
  },
  {
    title: '软件版本',
    dataIndex: 'softwareVersion',
    customRender({ text, record }) {
      return text + (record.versionCode ? `(${record.versionCode})` : '');
    },
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
  },
  {
    title: '推送结果',
    dataIndex: 'upgradeStatus',
    customRender({ text }) {
      return (
        <Tag color={text == 1 ? 'success' : 'error'}>
          {text == '1' ? '已推送' : '等待中'}
        </Tag>
      );
    },
  },
  {
    title: '状态',
    dataIndex: 'onlineStatus',
    valueEnum: { ...sysOnlineStatusEnum.value },
    customRender({ text }) {
      return (
        <Tag color={text == 0 ? 'error' : 'success'}>
          {
            sysOnlineStatusEnum.value?.[
              text as keyof typeof sysOnlineStatusEnum.value
            ]
          }
        </Tag>
      );
    },
  },
  {
    title: '监控开关',
    dataIndex: 'monitorStatus',
  },
]);
// const total = ref(0);
let timer: ReturnType<typeof setInterval> | null = null;

// watch(
//   () => queryParams.value.pageNum,
//   () => {
//     clearTimeout(timer);
//     handleTimer();
//   },
// );

// watch(
//   () => queryParams.value.pageSize,
//   () => {
//     clearTimeout(timer);
//     handleTimer();
//   },
// );

onMounted(() => {
  fetchDictsOfType(['sys_on_line_status']).then((res: any) => {
    const { sys_on_line_status } = res.data;
    sysOnlineStatusEnum.value = listToEnum(
      sys_on_line_status,
      'dictValue',
      'dictLabel',
    );
  });
  handleTimer();
});

onBeforeUnmount(() => {
  clearTimeout(timer);
});

// const tableRowClassName = ({ row }) => {
//   if (row.message) {
//     if (row.monitorStatus == 1 && row.message.indexOf('%') !== -1) {
//       return 'warning-row';
//     }
//   }
//   return '';
// };

// const changeSth = (row) => {
//   switchLoad.value = true;
//   const text = row.isSendMessage == '1' ? '是否启用？' : '是否关闭？';
//   $modal
//     .confirm(text)
//     .then(async () => {
//       await firmCancelMonitor({
//         versionPushId: row.versionPushId,
//         monitorStatus: row.monitorStatus,
//       });
//       switchLoad.value = false;
//       getList();
//     })
//     .catch(() => {
//       switchLoad.value = false;
//       getList();
//     });
// };
const tableRef = ref();
const _fetchSoftwareLogCheck = async (params: any) => {
  params.versionPushTotalId = props.update.versionPushTotalId;
  params.upgradeStatus = props.update.upgradeStatus;
  const res = await firmPushLogCheck({
    ...params,
  });

  return { rows: [...res.rows], total: res.total || 0 };
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onChangeMonitorStatus = (checked: string, record: any) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要${checked === '0' ? '停用' : '启用'}监控？`,
    onOk: async () => {
      await firmCancelMonitor({
        versionPushId: record.versionPushId,
        monitorStatus: checked,
      });
      sleep(() => tableRef.value.refresh());
    },
  });
};
// const getList = async () => {
//   console.log(props.row, 'this.row');
//   queryParams.value.versionPushTotalId = props.row.versionPushTotalId;
//   queryParams.value.upgradeStatus = props.row.upgradeStatus;
//   const res = await firmPushLogCheck(queryParams.value);
//   if (res.code == 200) {
//     let result = false;
//     if (res.rows.length > 0) {
//       result = res.rows.every((item) => item.message == '下载成功');
//     }
//     dataList.value = res.rows;
//     total.value = res.total;
//     loading.value = false;
//     console.log(result, 'result');
//     if (result) {
//       clearTimeout(timer);
//     }
//   }
// };

const handleTimer = () => {
  console.log('123');
  timer = setInterval(() => {
    tableRef.value.refresh();
  }, 5000);
};
</script>
<style lang="scss" scoped>
#updateFail {
  width: 100%;
  height: 100%;
}

::v-deep .el-table .warning-row {
  background: rgb(64, 158, 255, 0.3);
  // color: #ddd;
}
</style>
